//
//  MineViewController.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//


#import "MineViewController.h"

#import "TopBackView.h"

#import "OrderViewController.h"     //我的运单
#import "MineDetailVC.h"            ///用户详情
#import "MyWalletViewController.h"  ///我的钱包
#import "NewAboutViewController.h"  ///客服中心
#import "MyScoreViewController.h"   ///我的积分
#import "ShowViewController.h"      ///运费说明
#import "RootViewController.h"      ///根Vc


#import "MineCell.h"
#import "InstallCell1.h"
#import "QiniuSDK.h"


@interface MineViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    MineDetailVCDelegate
>

@property (nonatomic, strong) NSArray *buttonArray;

@property (nonatomic, strong) NSArray *imageArray;

@property (nonatomic, strong) UIScrollView *scrollView;



@property (nonatomic, strong) MineModel *mineModel;;

@property (nonatomic, weak) UITableView *tableView;

@end

@implementation MineViewController
{
    NSString *_token;
    BOOL _isViewLoad;
    TopBackView *_topBackView;
}

#pragma mark -
#pragma mark - Lazy
- (UIScrollView *)scrollView {
    if (!_scrollView) {
        
        CGRect frame = CGRectMake(0, NaviStatusH, screenWidth, screenHeight);
        
        _scrollView = [[UIScrollView alloc]initWithFrame:frame];
        
        _scrollView.backgroundColor = GrayColor;
        
        _scrollView.contentSize = CGSizeMake(screenWidth, screenHeight + 1);
        
        
        frame = CGRectMake(0, 0, screenWidth, screenHeight - 64 - 55 * kHeight);
        
        UITableView * tableView = [[UITableView alloc]initWithFrame:frame];
        
        self.tableView = tableView;
        
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.tableFooterView = [[UIView alloc]init];
        tableView.backgroundColor = GrayColor;
        
        [self.scrollView addSubview:tableView];
        
    }
    return _scrollView;
}

- (NSArray *)buttonArray {
    if (!_buttonArray)
    {
//        _buttonArray =  @[@"我的运单",
//                          @"我的钱包",
//                          @"运费说明",
//                          @"客服中心"];
        _buttonArray =  @[@"我的运单",
                          @"运费说明",
                          @"客服中心"];

    }
    return _buttonArray;
}

- (NSArray *)imageArray {
    if (!_imageArray)
    {
        _imageArray = @[@"my_icon_list",
                        @"priceshow",
                        @"my_icon_about"];
    }
    return _imageArray;
}

#pragma mark -
#pragma mark - View初始化

- (void)viewDidLoad {
   
    [super viewDidLoad];
    _isViewLoad = YES;                               /// 判断是否是viewDidLoad而来
    [self getServerDatasIsNeedReloadHeadImage:YES];  /// 获取用户信息(需要刷新头像)
    [self addNotiManger];                            /// 添加通知管理者
    [self setUpUI];                                  /// 布局View
}

- (void)setUpUI {
    
    self.navigationController.navigationBarHidden = YES;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
    
/// 1. 添加导航栏
    CGRect frame = CGRectMake(0, 0, screenWidth, 64);
    
    _topBackView = [[TopBackView alloc] initWithFrame:frame
                                                title:@"个人中心"];
    _topBackView.leftButton.hidden = YES;

    _topBackView.rightButton.hidden = YES;
    
    [self.view addSubview:_topBackView];
    
/// 2. 添加scrollView
    [self.view addSubview:self.scrollView];
}



#pragma mark - 获取服务器数据
- (void)getServerDatasIsNeedReloadHeadImage:(BOOL)isReload {
    
    __weak typeof(self) weakSelf = self;
    
      NSLog(@"%@",user_info );
    
    [Common requestWithUrlString:user_info contentType:application_json errorShow:YES finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue]) {
            
            NSDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:responseObj[@"data"]];
            
            weakSelf.mineModel = [MineModel mj_objectWithKeyValues:dict];
            
        
            [weakSelf getValueString:isReload];
            
            
        }
        else
        {
            [WKProgressHUD popMessage:responseObj[@"message"]
                               inView:weakSelf.view
                             duration:1.5
                             animated:YES];
            
        }
        
    } failed:^(NSString *errorMsg) {
        
        NSLog(@"%@",errorMsg);
    }];
    
}


//查询用户信息
- (void)checkUserOnline{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSString *valueString = [userDefaults objectForKey:@"login"];
    
    if (valueString == nil)
    {
        UIButton *button = (UIButton *)[self.view viewWithTag:600];
        
        button.hidden = YES;
    }
    else
    {
        UIButton *button = (UIButton *)[self.view viewWithTag:600];
        
        button.hidden = NO;
        
        NSString  *string = [NSString stringWithFormat:@"%@user",Main_interface];
        
         __weak typeof(self) weakSelf = self;
        
        [Common requestWithUrlString:string
                         contentType:application_json
                           errorShow:YES
                            finished:^(id responseObj) {
                                
                                if ([responseObj[@"success"] boolValue]) {
                                    
                                    UIButton *button = (UIButton *)[weakSelf.view viewWithTag:600];
                                    
                                    NSString *valueString = [NSString stringWithFormat:@"%@",responseObj[@"data"][@"userStatus"]];
                                    
                                    if ( [valueString isEqualToString:@"10"]) {
                                        
                                        [button setTitle:@"下线" forState:UIControlStateNormal];
                                        [button setTitleColor:YellowColor forState:UIControlStateNormal];
                                        button.userInteractionEnabled = YES;
                                        
                                    }
                                    else
                                    {
                                        [button setTitle:@"已下线" forState:UIControlStateNormal];
                                        [button setTitleColor:fontGrayColor forState:UIControlStateNormal];
                                        button.userInteractionEnabled = NO;
                                        
                                    }
                                }
                                
                            } failed:^(NSString *errorMsg) {
                                NSLog(@"%@",errorMsg);
                            }];
    }
}


#pragma mark 赋值方法

/**
  isReload : 作用判断是否需要刷新头像

 @param isReload  YES : 需要  NO 不需要；
 
 */
- (void)getValueString:(BOOL)isReload{
 
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
   
    MineCell *cell = [self.tableView cellForRowAtIndexPath:index];
    
    if (isReload != NO)
    {
//////viewDidLoad
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:self.mineModel.phone forKey:@"phone"];
        
        
        if ([self.mineModel.pic isEqual:[NSNull null]])
        {
            cell.ImageView.image = [UIImage imageNamed:@"home_portrait"];
        }
        else
        {
            [cell.ImageView sd_setImageWithURL:[NSURL URLWithString:self.mineModel.pic]
                              placeholderImage:[UIImage imageNamed:@"home_portrait"]];
            
        }
        
    }
    else
    {
//////viewWillAppear
    }
    cell.mineModel = self.mineModel;
    
}



/**
 视图即将展示
 */
- (void)viewWillAppear:(BOOL)animated{
    

    [super viewWillAppear:animated];
    
    RootViewController *rootVC = [RootViewController defaultsTabBar];
    
    [rootVC setTabBarHidden:NO];
    
    if (!_isViewLoad)
    {
        //修改信息后 重新请求数据
        [self getServerDatasIsNeedReloadHeadImage:NO];
        
        [self checkUserOnline];
    }
    
}
/**
 视图即将消失
 */
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    _isViewLoad = NO;
  
}




#pragma mark -
#pragma mark - 添加通知管理者
- (void)addNotiManger {
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reloadUI)
                                                 name:@"creatViews"
                                               object:nil];
}
#pragma mark - MineDetailVCDelegate协议
- (void)mineDetailSaveNewInfo{
    [self reloadUI];
}

- (void)reloadUI {
    _isViewLoad = YES;
    [self getServerDatasIsNeedReloadHeadImage:YES];
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"creatViews" object:nil];
}





#pragma mark -
#pragma mark - 表单协议
- (CGFloat)tableView:(UITableView *)tableView
heightForFooterInSection:(NSInteger)section{
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView
heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView
 numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    } else {
        
        return self.buttonArray.count;
        
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section)
    {
        case 0:
        {
            MineCell *cell = [tableView dequeueReusableCellWithIdentifier:@"mineCell"];
            if (!cell)
            {
                cell = [[MineCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"mineCell"];
            }
            
            cell.ImageView.image = [UIImage imageNamed:@"home_portrait"];
            
            
            cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"personal_arrow"]];
            
            return cell;
            
        }
            break;
        default:
        {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"buttonCell"];
            if (!cell)
            {
                cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"buttonCell"];
            }
            
            cell.textLabel.text = self.buttonArray[indexPath.row];
            
            cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"personal_arrow"]];
            
            cell.textLabel.font = Font(13);
            cell.textLabel.textColor = littleBlackColor;
            cell.imageView.image = [UIImage imageNamed:self.imageArray[indexPath.row]];
            return cell;
        }
            break;
    }
}

- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return  78 * kWidth;
    } else {
        return  cellHeight;
    }
    
}

- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if ([Common judgeUsertype]) {
        
        if (indexPath.section == 0) {
            MineDetailVC *detailVC = [[MineDetailVC alloc]init];
            detailVC.delegate = self;
            [Common isLogin:self andPush:detailVC];
            
        }
        
        //我的运单
        if (indexPath.row == 0 &&indexPath.section == 1) {
            OrderViewController *missionVC = [[OrderViewController alloc]init];
            missionVC.hide = @"1";
            [Common isLogin:self andPush:missionVC];
        }
        //我的钱包
        //    if (indexPath.row == 1 &&indexPath.section == 1) {
        //        MyWalletViewController * wallet = [[MyWalletViewController alloc]init];
        //
        //        [Common isLogin:self andPush:wallet];
        //    }
        
        
        
        //价格说明
        if (indexPath.row == 1 &&indexPath.section == 1) {
            
            ShowViewController *showVC = [[ShowViewController alloc]init];
            
            [self.navigationController pushViewController:showVC animated:YES];
            
            
        }
        
        //客服中心
        if (indexPath.row == 2 &&indexPath.section == 1) {
            
            NewAboutViewController *aboutVC = [[NewAboutViewController alloc]init];
            
            [self.navigationController pushViewController:aboutVC animated:YES];
            
            
        }
        
        
    } else {
        if (indexPath.section == 0) {
            MineDetailVC *detailVC = [[MineDetailVC alloc]init];
            
            [Common isLogin:self andPush:detailVC];
            
        }
        
        //我的运单
        if (indexPath.row == 0 &&indexPath.section == 1) {
            OrderViewController *missionVC = [[OrderViewController alloc]init];
            missionVC.hide = @"1";
            [Common isLogin:self andPush:missionVC];
        }
        
        //客服中心
        if (indexPath.row == 1 &&indexPath.section == 1) {
            
            
            NewAboutViewController *aboutVC = [[NewAboutViewController alloc]init];
            
            [self.navigationController pushViewController:aboutVC animated:YES];
            
            
        }
        
        
    }
    
    
    
}

- (UIView *)tableView:(UITableView *)tableView
viewForFooterInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]init];
    
    view.backgroundColor = GrayColor;
    
    return view;
}

@end
